package com.atguigu.study.service.impl;

import com.atguigu.study.annotations.MyRedisCache;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.study.pojo.User;
import com.atguigu.study.service.UserService;
import com.atguigu.study.mapper.UserMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.Serializable;

/**
* @author 卫国夫
* @description 针对表【t_user(用户表)】的数据库操作Service实现
* @createDate 2025-07-31 10:33:01
*/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    public static final String CACHE_KEY_USER = "user:";

    @Resource
    private UserMapper userMapper;
    @Resource
    private RedisTemplate redisTemplate;


    @Override
    public boolean save(User user)
    {
        boolean retValue = false;

        log.info("插入之前user:{}", user);
        retValue = super.save(user);
        log.info("插入之后user:{}", user);
        log.info("=================================");

        if (retValue) {
            //到数据库里面，重新捞出新数据出来，做缓存
            user = this.userMapper.selectById(user.getId());
            //缓存key
            String key = CACHE_KEY_USER + user.getId();
            //往mysql里面插入成功随后再从mysql查询出来，再插入redis
            redisTemplate.opsForValue().set(key, user);
        }

        return retValue;
    }

    /*@Override
    public User getById(Serializable id)
    {
        User user = null;
        //缓存key
        String key = CACHE_KEY_USER + id;

        //1 查询redis
        user = (User) redisTemplate.opsForValue().get(key);

        //2 redis有直接返回，redis无则进一步查询mysql
        if (user == null)
        {
            //从mysql查出来user
            user = this.userMapper.selectById(id);

            //3 mysql有，redis无
            if (user != null)
            {
                //把mysql捞到的数据写入redis，方便下次查询能redis命中。
                redisTemplate.opsForValue().set(key, user);
            }
        }
        return user;
    }*/

    /**
     * 会将返回值存进redis里，key生成规则需要程序员用SpEL表达式自己指定，value就是程序从mysql查出并返回的user
     * redis的key 等于  keyPrefix:matchValue
     * @param id 主键ID
     * @return
     */
    @Override
    @MyRedisCache(keyPrefix = "user",matchValue = "#id")
    public User getById(Serializable id)
    {
        //从mysql查出来user 如何将缓存代码从业务代码中剥离，促使业务代码更简洁更易维护
        return this.userMapper.selectById(id);
    }

}




